package com.iweibo.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import com.weibo.sdk.android.net.RequestListener;

import android.graphics.drawable.Drawable;

/**
 * 网络工具处理类
 * 
 * @author nibo
 * @date 2012-10-22
 * 
 */
public class NetUtil {

	/**
	 * 获取网络图片
	 * 
	 * @param url
	 *            图片地址
	 * @return Drawable对象
	 * @throws IOException
	 */
	public static Drawable getNetImage(URL url) throws IOException {
		HttpURLConnection urlConnection = (HttpURLConnection) url
				.openConnection();
		return Drawable.createFromStream(urlConnection.getInputStream(),
				"image");
	}

	/**
	 * 获取网络图片
	 * 
	 * @param url
	 *            图片地址
	 * @return byte[]数组
	 * @throws IOException
	 */
	public static void getNetImageByte(final URL url, final RequestListener listener) {
		
		new Thread() {
			@Override
			public void run() {
				HttpURLConnection urlConnection = null;
				try {
					urlConnection = (HttpURLConnection) url.openConnection();
					byte[] imageByte = new byte[urlConnection.getContentLength()];
					urlConnection.getInputStream().read(imageByte);
					listener.onComplete(imageByte);
				} catch (IOException e) {
					listener.onIOException(e);
				}
			}
		}.start();
	}

}
